package server

import (
	"errors"
	"fmt"
	"github.com/google/uuid"
	"gorm.io/gorm"
	"log"
	"onerk4/zk3/common/cron"
	"onerk4/zk3/common/dao/mysql"
	"onerk4/zk3/common/global"
	"onerk4/zk3/common/model"
	"onerk4/zk3/common/pkg"
	"onerk4/zk3/common/proto/user"
	"time"
)

func Register(req *user.RegisterOrLoginRequest) (*user.RegisterOrLoginResponse, error) {
	queryUser, err := mysql.QueryUser(req.Mobile)
	if err != nil {
		log.Fatalf("查询失败: %v", err)
		return nil, err
	}

	if queryUser.ID != 0 {
		return nil, errors.New("改手机号已被注册")
	}

	tx := global.DB.Begin()

	u := model.User{
		Model:    gorm.Model{},
		Mobile:   req.Mobile,
		Password: req.Password,
	}
	err = mysql.CreateUser(&u)
	if err != nil {
		tx.Rollback()
		log.Fatalf("注册失败: %v", err)
		return nil, err
	}

	c := model.Coupon{
		Model:   gorm.Model{},
		UId:     int(u.ID),
		Coupons: "满100减5的优惠券",
	}
	err = mysql.CreateCoupon(&c)
	if err != nil {
		tx.Rollback()
		log.Fatalf("优惠卷入库失败: %v", err)
		return nil, err
	}
	tx.Commit()

	return &user.RegisterOrLoginResponse{Success: "用户注册成功"}, nil
}

func Login(req *user.RegisterOrLoginRequest) (*user.RegisterOrLoginResponse, error) {
	queryUser, err := mysql.QueryUser(req.Mobile)
	if err != nil {
		log.Fatalf("查询失败: %v", err)
		return nil, err
	}

	if queryUser.ID == 0 {
		return nil, errors.New("改手机号还未被注册")
	}

	if queryUser.Password != req.Password {
		return nil, errors.New("密码错误")
	}

	claims := pkg.CustomClaims{ID: uint(queryUser.ID)}
	token, err := pkg.NewJWT("2209a").CreateToken(claims)
	if err != nil {
		log.Fatalf("token生成失败: %v", err)
		return nil, err
	}

	return &user.RegisterOrLoginResponse{Success: token}, nil
}

func AddStudyPlanShow(req *user.AddStudyPlanShowRequest) (*user.AddStudyPlanShowResponse, error) {
	info, err := mysql.QueryStudyPlanInfo(req.StudyPlanId)
	if err != nil {
		log.Fatalf("查询失败: %v", err)
		return nil, err
	}

	us := model.UserStudyPlan{
		Model:       gorm.Model{},
		UId:         int(req.UserId),
		StudyPlanId: int(req.StudyPlanId),
		Course:      info.Course,
		Info:        info.Info,
		Price:       info.Price,
	}
	err = mysql.AddStudyPlanShow(&us)
	if err != nil {
		log.Fatalf("添加课程失败: %v", err)
		return nil, err
	}

	return &user.AddStudyPlanShowResponse{Success: "添加课程成功"}, nil
}

func DelStudyPlanShow(req *user.DelStudyPlanShowRequest) (*user.DelStudyPlanShowResponse, error) {
	info, err := mysql.QueryUserStudyPlanInfo(req.StudyPlanId, req.UserId)
	if err != nil {
		log.Fatalf("查询失败: %v", err)
		return nil, err
	}

	if info.ID == 0 {
		return nil, errors.New("没有该课程")
	}

	err = mysql.DelStudyPlanShow(req.StudyPlanId, req.UserId)
	if err != nil {
		log.Fatalf("删除失败: %v", err)
		return nil, err
	}

	return &user.DelStudyPlanShowResponse{Success: "删除课程成功"}, nil
}

func CreateOrder(req *user.CreateOrderRequest) (*user.CreateOrderResponse, error) {
	info, err := mysql.QueryUserStudyPlanInfo(req.StudyPlanId, req.UserId)
	if err != nil {
		log.Fatalf("查询失败: %v", err)
		return nil, err
	}
	coupon, err := mysql.QueryUserCoupon(req.UserId)
	if err != nil {
		return nil, err
	}
	orderSn := uuid.New().String() + time.Now().Format("20060102150405")
	if coupon.ID == 0 {
		o := model.Order{
			Model:               gorm.Model{},
			UId:                 int(req.UserId),
			OrderNum:            orderSn,
			StudyPlanId:         int(req.StudyPlanId),
			TotalAmount:         info.Price,
			DiscountAmount:      0.00,
			ActualPaymentAmount: info.Price,
			Status:              3,
		}
		err := mysql.CreateOrder(&o)
		if err != nil {
			return nil, err
		}
		ActualPaymentAmount := fmt.Sprintf("%.2f", info.Price)
		pay := pkg.Pay(info.Course, orderSn, ActualPaymentAmount)

		return &user.CreateOrderResponse{Success: pay}, nil
	}
	tx := global.DB.Begin()
	o := model.Order{
		Model:               gorm.Model{},
		UId:                 int(req.UserId),
		OrderNum:            orderSn,
		StudyPlanId:         int(req.StudyPlanId),
		TotalAmount:         info.Price,
		DiscountAmount:      5.00,
		ActualPaymentAmount: info.Price - 5.00,
		Status:              3,
	}
	err = mysql.CreateOrder(&o)
	if err != nil {
		tx.Rollback()
		return nil, err
	}

	err = mysql.DelUserCoupon(req.UserId, req.UserCoupon)
	if err != nil {
		tx.Rollback()
		log.Fatalf("销毁优惠卷失败: %v", err)
		return nil, err
	}

	ActualPaymentAmount := fmt.Sprintf("%.2f", info.Price-5.00)
	pay := pkg.Pay(info.Course, orderSn, ActualPaymentAmount)

	go func() {
		cron.Update(orderSn)
	}()

	return &user.CreateOrderResponse{Success: pay}, nil
}
